﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using App.Utilities.Web.Handlers;
using System.Data;
using CRMBiz;
using Newtonsoft.Json;
using System.Globalization;

namespace CRMWeb.WebServices
{
    /// <summary>
    /// Summary description for DuplicateContactDetective
    /// </summary>
    public class DuplicateContactDetective : BaseHandler
    {

        public override void OnMethodInvoke(OnMethodInvokeArgs e)
        {
            context.Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
            context.Response.Cache.SetExpires(DateTime.MinValue);
            context.Response.Cache.SetNoStore();
            SetResponseContentType(ResponseContentTypes.HTML);
        }

        public override void AfterMethodInvoke(object result)
        {
            base.AfterMethodInvoke(result);
        }

        public void GetDuplicateContactAll(string searchfield)
        {
            try
            {
                var pageIndex = string.IsNullOrEmpty(context.Request["page"]) ? 1 : int.Parse(context.Request["page"]);
                var pageSize = string.IsNullOrEmpty(context.Request["rows"]) ? 10 : int.Parse(context.Request["rows"]);
                DataSet ds = DuplicateContactHandler.SelectDuplicateContact(pageIndex, pageSize, searchfield);
                var total = (ds.Tables[0].Rows.Count > 0) ? Convert.ToInt32(ds.Tables[0].Rows[0]["Total"]) : 0;
                string strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                strJson = "{\"total\":\"" + total.ToString() + "\",\"rows\":" + strJson + "}";

                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void GetDuplicatedContactID(string field, string value)
        {
            try
            {
                DataSet ds = DuplicateContactHandler.GetDuplicatClients(field, value);
                string strJson = JsonConvert.SerializeObject(ds.Tables[0]);
                context.Response.Write(strJson);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void RemoveDuplicateContact(string ContactsToDuplicate, int DupWithContact)
        {
            try
            {
                DuplicateContactHandler.DeleteDuplicateContact(ContactsToDuplicate, DupWithContact);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void PrepareDataGrid(int ContactID, string FirstName, string SurName, string DateBirth, string EMail, string secondEmailAddress, string Mobile, string Street, string State, string Suburb)
        {
            bool matched = false;
            string option = string.Empty;
            List<int> unmatchedRow = new List<int>();
            string datagrid = "<table id=\"dgCompareDuplicate\"  style=\"width: auto; height: 350px;\">";
            try
            {
                DataTable dt = DuplicateContactHandler.CompareDuplicateContact(ContactID, FirstName, SurName, DateBirth, EMail,secondEmailAddress, Mobile, Street, State, Suburb);
                bool[,] matchedCell = new bool[dt.Rows.Count, dt.Columns.Count];
                if (dt.Columns.Count > 20)
                {
                    datagrid = "0";
                    context.Response.Write(datagrid);
                    return;
                }
                if (dt.Columns.Count > 2)
                {
                    dt.Columns.Add("Compare");
                    for (int row = 0; row <= 11; row++)
                    {
                        for (int col = 1; col < dt.Columns.Count - 2; col++)
                        {
                            string str1 = dt.Rows[row][col].ToString().Trim();
                            string str2 = dt.Rows[row][col + 1].ToString().Trim();
                            str1 = str1.ToLower();
                            str2 = str2.ToLower();
                            if (str1.Equals(str2))
                            {
                                matched = true;
                                continue;
                            }
                            else
                            {
                                matched = false;
                                break;
                            }
                        }
                        if (matched == true)
                            dt.Rows[row]["Compare"] = 1;
                        else if (matched == false)
                        {
                            dt.Rows[row]["Compare"] = 0;
                            unmatchedRow.Add(row);
                            // Set Green Color where value matched
                            var CurrRow = string.Join(",", dt.Rows[row].ItemArray);
                            string[] rowArray = CurrRow.Split(',');
                            for (int i = 1; i < rowArray.Length - 1; i++)
                            {
                                for (int j = i + 1; j < rowArray.Length; j++)
                                {
                                    if (string.IsNullOrEmpty(rowArray[i]) || string.IsNullOrEmpty(rowArray[j]))
                                        continue;
                                    else
                                    {
                                        if (rowArray[i].Equals(rowArray[j]))
                                        {
                                            matchedCell[row, i] = true;
                                            matchedCell[row, j] = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // Draw Datagrid Columns Header
                datagrid += "<th><td style=\"width:150px;text-align:center;font-family:cambira\"></td>";
                for (int x = 1; x < dt.Columns.Count; x++)
                {
                    if (dt.Columns[x].ColumnName == ContactID.ToString())
                        datagrid += "<td style=\"width:150px;height:30px;text-align:center\"><lable id=\"lbl" + ContactID + "\" style=\"font-family:arial;font-size:medium;color:maroon\"> <b> Current Client </b> </lable> </td> ";
                    else if (dt.Columns[x].ColumnName == "Compare")
                        datagrid += "<td style=\"width:80px;height:30px;text-align:center\"><lable id=\"lbl" + dt.Columns[x].ColumnName.ToString() + "\" style=\"font-family:arial;font-size:medium\"><b>" + dt.Columns[x].ColumnName.ToString() + " </b> </lable> </td>";
                    else
                        datagrid += "<td style=\"width:150px;height:30px;text-align:center\"><lable id=\"lbl" + dt.Columns[x].ColumnName.ToString() + "\" style=\"font-family:arial;font-size:medium\"><b> Client ID: " + dt.Columns[x].ColumnName.ToString() + " </b> </lable> </td>";
                }
                datagrid += "</th>";
                for (int row = 0; row < dt.Rows.Count; row++)
                {
                    datagrid += "<tr>";
                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        if (col == 0)
                        {
                            switch (row)
                            {
                                case 0:
                                    datagrid += "<td rowspan=\"12\" style=\"width:100px;color:maroon;text-align:center;font-family:verdana;font-size:14px\"> Client Profile </td> <td style=\"width:200px;text-align:left;font-family:cambira\"> <b> " + dt.Rows[row][col].ToString() + "   " + " </b> </td>";
                                    break;
                                case 12:
                                    datagrid += "<td rowspan=\"5\" style=\"width:100px;color:maroon;text-align:center;font-family:verdana;font-size:14px\"> Application Profile </td> <td style=\"width:200px;text-align:left;font-family:cambira\"> <b> " + dt.Rows[row][col].ToString() + "   " + " </b> </td>";
                                    break;
                                case 17:
                                    datagrid += "<td rowspan=\"4\" style=\"width:100px;color:maroon;text-align:center;font-family:verdana;font-size:14px\">   </td> <td style=\"width:200px;text-align:left;font-family:cambira\"> <b> " + dt.Rows[row][col].ToString() + "   " + " </b> </td>";
                                    break;
                                case 21:
                                    datagrid += "<td rowspan=\"2\" style=\"width:100px;color:maroon;text-align:center;font-family:verdana;font-size:14px\"> Action </td> <td style=\"width:200px;text-align:left;font-family:cambira\"> <b> " + dt.Rows[row][col].ToString() + "   " + " </b> </td>";
                                    break;
                                default:
                                    datagrid += "<td style=\"width:120px;text-align:left;font-family:cambira\"> <b> " + dt.Rows[row][col].ToString() + "   " + " </b> </td>";
                                    break;
                            }
                        }
                        else
                        {
                            if (row < 12)
                            {
                                if (dt.Columns[col].ColumnName == "Compare")
                                {
                                    if ((string)dt.Rows[row][col].ToString() == "0")
                                        datagrid += "<td style=\"width:100px;text-align:center\"><img src=\"../../Media/cancel.png\" style=\" width:auto;height:auto\"></td>";
                                    else if ((string)dt.Rows[row][dt.Columns.Count - 1].ToString() == "1")
                                        datagrid += "<td style=\"width:100px;text-align:center\"><img src=\"../../Media/ok.png\" style=\" width:auto;height:auto\"></td></td>";
                                }
                                else
                                {
                                    if (unmatchedRow.Contains(row))
                                    {
                                        if (matchedCell[row, col] == true)
                                            datagrid += "<td style=\"width:150px;text-align:left;background-color:lightgreen\">" + dt.Rows[row][col].ToString() + "</td>";
                                        else
                                            datagrid += "<td style=\"width:150px;text-align:left;background-color:pink\">" + dt.Rows[row][col].ToString() + "</td>";
                                    }
                                    else
                                        datagrid += "<td style=\"width:150px;text-align:left\">" + dt.Rows[row][col].ToString() + "</td>";
                                }
                            }
                            else if (row >= 12 && col < dt.Columns.Count - 1)
                            {
                                switch (row)
                                {
                                    case 12:
                                        datagrid += "<td style=\"width:150px;text-align:center\"> <a href=\"#\" onclick=\"openApplicationForm('" + dt.Rows[row][col].ToString() + "')\" > FormID:" + dt.Rows[row][col].ToString() + " </a> </td>";
                                        break;
                                    case 13:
                                        datagrid += "<td style=\"width:150px;text-align:left\"> " + dt.Rows[row][col].ToString() + " </td>";
                                        break;
                                    case 14:
                                        datagrid += "<td style=\"width:150px;text-align:left;background-color:orange\"> <b>" + dt.Rows[row][col].ToString() + " </b></td>";
                                        break;
                                    case 15:
                                        {
                                            option = string.Empty;
                                            DataSet ds = ApplicationContactHandler.GetApplicationForClient(Convert.ToInt32(dt.Columns[col].ColumnName));
                                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                                            {
                                                option += "<option value=\" " + ds.Tables[0].Rows[i]["app_id"].ToString() + "\">" + ds.Tables[0].Rows[i]["app_id"].ToString() + "</option>";
                                            }
                                            datagrid += "<td style=\"width:150px;text-align:center\"><select   id=\"cmbViewApp" + dt.Columns[col].ColumnName + "\" onchange=\" getAppData('" + dt.Columns[col].ColumnName + "')\" > " + option + " </select>" +
                                                "<a href=\"#\" onclick=\"ViewApp('" + dt.Columns[col].ColumnName + "')\" >View </a></td>";
                                            break;
                                        }

                                    case 16:
                                        datagrid += "<td style=\"width:150px;text-align:left\"><lable id=\"lblloanAmt" + dt.Columns[col].ColumnName.ToString() + "\" ></lable> </td>";
                                        break;
                                    case 17:
                                        datagrid += "<td style=\"width:150px;text-align:left\"><lable id=\"lblDate" + dt.Columns[col].ColumnName.ToString() + "\" ></lable> </td>";
                                        break;
                                    case 18:
                                        datagrid += "<td style=\"width:150px;text-align:left\"><lable id=\"lblSecurity" + dt.Columns[col].ColumnName.ToString() + "\" ></lable> </td>";
                                        break;
                                    case 19:
                                        datagrid += "<td style=\"width:150px;text-align:left;background-color:orange\"> <b>" + dt.Rows[row][col].ToString() + " </b></td>";
                                        break;
                                    case 20:
                                        datagrid += "<td style=\"width:150px;text-align:center\">  <select id=\"cmbgrp" + dt.Columns[col].ColumnName + "\" style=\"width: 50px\">" +
                                                        "<option value=\"1\">1</option><option value=\"2\">2</option> <option value=\"3\">3</option>" +
                                                        "<option value=\"4\">4</option><option value=\"5\">5</option>  " + "</select></td>";
                                        break;
                                    case 21:
                                        datagrid += "<td style=\"width:150px;text-align:center\">  <select id=\"cmbClientAction" + dt.Columns[col].ColumnName + "\" " +
                                                        " style=\"width: 70px\" >" +
                                                        "<option value=\"Keep\">Keep</option><option value=\"Delete\">Delete</option></select></td>";
                                        break;
                                    case 22:
                                        datagrid += "<td style=\"width:150px;text-align:center\"> <select class=\"easyui-combogrid\" style=\"width:100px\" id=\"cmbDelApp" + dt.Columns[col].ColumnName + "\" > </select>";
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                    }
                    datagrid += "</tr>";
                }
                if (dt.Columns.Count > 2)
                    datagrid += "</table><div id=\"divbtn\" style=\"text-align:center;height:30px;width:100% \"> <a id=\"lnkSave\" onclick=\"saveChanges()\" iconcls=\"icon-ok\" class=\"easyui-linkbutton l-btn\" href=\"javascript:void(0)\"><span class=\"l-btn-left\"><span class=\"l-btn-text icon-ok l-btn-icon-left\"> Submit Changes </span></span></a></div>";
                else
                    datagrid += "</table>";
                context.Response.Write(datagrid);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void DeleteMultipleApplication(string applications)
        {
            bool flag = false;
            try
            {
                flag = DuplicateContactHandler.DeleteMultipleApplication(applications);
                context.Response.Write(flag);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void DuplicateMultipleClient(string clients, int duplicateWith)
        {
            bool flag = false;
            try
            {
                flag = DuplicateContactHandler.duplicateMultipleClient(clients, duplicateWith);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}